package cn.hyxy.hadoop;

import java.net.URI;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler;
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class Demo19_TotalSortMR extends Configured implements Tool {

	@Override
	public int run(String[] args) throws Exception {
		if (args.length != 2) {
			System.out.println("usage : in out...");
			return -1;
		}
		Configuration config = getConf();
		FileSystem fs = FileSystem.get(config);
		Path path = new Path(args[1]);
		if (fs.exists(path)) {
			fs.delete(path, true);
		}

		Job job = Job.getInstance(config, "TotalSort");
		job.setJarByClass(getClass());

		job.setMapperClass(Mapper.class);// 默认的！！！
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(Text.class);
		job.setReducerClass(Reducer.class);
		job.setInputFormatClass(KeyValueTextInputFormat.class);
		KeyValueTextInputFormat.addInputPath(job, new Path(args[0]));
		FileOutputFormat.setOutputPath(job, path);

		job.setNumReduceTasks(2);
		// 设置全排序(全排序的文件必须是经过半排序的！！！
		job.setPartitionerClass(TotalOrderPartitioner.class);
		// 以下是“采样”
		//freq:的值建议从0.1到0.5
        //numberSamples:大于等于splits的个数，建议大于等于reducer的个数
        //maxSplits:等于splits个数
		InputSampler.Sampler<Text, Text> sampler = new InputSampler.RandomSampler<Text, Text>(0.1, 2, 2);
		InputSampler.writePartitionFile(job, sampler);

		// 可选的缓存
		String partitonerfile = TotalOrderPartitioner.getPartitionFile(config);
		System.out.println("缓存的文件：" + partitonerfile);
		job.addCacheFile(new URI(partitonerfile));

		return job.waitForCompletion(true) ? 0 : 1;
	}

	public static void main(String[] args) throws Exception {
		int code = ToolRunner.run(new Demo19_TotalSortMR(), args);
		System.exit(code);
	}
}
